<template>
  <!---购物车商品-->
  <template v-if="goodslist.length>0">
    <template v-for="(goods,index) in goodslist" :key="index">
      <div class="item">
        <div>名称:{{ goods.name }}</div>
        <div>价格:￥<span style="color: #f00">{{ goods.price }}</span></div>
        <div>
          <span class="disable" @click="dec(goods,index)">-</span>
          <input type="number" :value="goods.num">
          <!--点击增加数量 -->
          <span class="enable" v-on:click="goods.num++">+</span>
        </div>
      </div>
    </template>
  </template>
  <div v-else> 暂无商品，请去购物</div>
  <br><br>
  商品总价格：{{ totalprice }}<br>
</template>
<script setup>
import {reactive, ref, watch, watchEffect} from 'vue'

const totalprice = ref(0)
const goodslist = reactive([
  {
    name: "华为手机",
    price: 999,
    num: 2
  }, {
    name: "华为手表",
    price: 499,
    num: 3
  }
])

function dec(goods, index) {
  goods.num--
  if (goods.num === 0) {
    goodslist.splice(index, 1)
  }
}

watchEffect(async () => {
  let total = 0;
  //遍历商品
  goodslist.forEach(el => {
    //取出当前商品的价格和数量
    let price = el.price
    el.num = el.num < 0 ? 0 : el.num
    let num = el.num
    total += price * num
  })
  totalprice.value = total
})
</script>
<style scoped>
span {
  display: inline-block;
  width: 20px;
  height: 20px;
  border: #eee solid 1px;
  font-size: 16px;
  text-align: center;
  line-height: 20px;

}

input {
  width: 50px;
  border-style: none;
  border-bottom: #333 solid 2px;
  margin: 0 10px;
  text-align: center;
}

.enable {
  background-color: #f00;
  color: #fff;
}

.disable {
  background-color: #ccc;
  color: #999;
}

.item {

  width: 200px;
  height: 100px;
  border: #ccc solid 1px;
  margin: 20px 0;
}
</style>
